package com.hk.controller;

import com.hk.entity.Result;
import com.hk.service.AdminService;
import com.hk.service.StuService;
import com.hk.utils.AliOSSUtils;
import com.hk.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    /**
     * 管理员头像上传
     * @param file
     * @param Authorization
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam(value = "file",required = false) MultipartFile file, @RequestHeader("token") String Authorization) throws IOException {

        // 从token头中提取JWT令牌
        String token = Authorization;
        log.info("token: {}", token);
        // 解析JWT令牌并提取管理员ID
        Map<String, Object> claims = JwtUtils.parseJWT(token);
        String adminId = (String) claims.get("adminId");
        log.info("管理员ID: {}", adminId);
        if (file == null) {
            log.info("文件未上传");
            return Result.error("文件未上传");
        }
        log.info("文件上传, 文件名: {}", file.getOriginalFilename());
        //调用阿里云OSS工具类进行文件上传
        String url = aliOSSUtils.upload(file);
        adminService.uploadUrl(url,adminId);
        log.info("文件上传完成,文件访问的url: {}", url);
        return Result.success(url);
    }

    @Autowired
    private StuService stuService;
    /**
     * 学生头像上传
     * @param file
     * @param authorization
     * @return
     * @throws IOException
     */
    @PostMapping("/stu/upload")
    public Result uploadStu(@RequestParam(value = "file",required = false) MultipartFile file, @RequestHeader("token") String authorization) throws IOException {

        // 从token头中提取JWT令牌
        String token = authorization;

        // 解析JWT令牌并提取管理员ID
        Map<String, Object> claims = JwtUtils.parseJWT(token);
        String stuId = (String) claims.get("stuId");
        log.info("文件上传, 文件名: {}", file.getOriginalFilename());
        //调用阿里云OSS工具类进行文件上传
        String url = aliOSSUtils.upload(file);
        stuService.uploadUrl(url,stuId);
        log.info("文件上传完成,文件访问的url: {}", url);
        return Result.success(url);
    }


}
